from django.contrib.auth.decorators import login_required
from django.views.generic import list_detail
from hosting.domains.models import SOA, RR
from hosting.domains.forms import SOAForm, RRForm
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
# Create your views here.

def _edit_form(self):
    return RRForm(auto_id=False, instance=self)

RR.edit_form = property(_edit_form)

def _edit_form(self):
    return SOAForm(auto_id=False, instance=self)

SOA.edit_form = property(_edit_form)

@login_required
def list_domains(request):
    return list_detail.object_list(
        request,
        queryset = SOA.objects.filter(user=request.user),
#        template_object_name = 'soa',
#        template_name = 'domains/soa_list.html',
    )

@login_required
def domain_detail(request, domain_id):
    extra_context = { 'form': RRForm(initial={'zone': domain_id}) }
    if "status" in request.session:
        extra_context['status'] = request.session.get("status")
        extra_context['message'] = request.session.get("message")
        del request.session["status"]
        del request.session["message"]
    return list_detail.object_list(
        request,
        queryset = SOA.objects.filter(user=request.user, id=domain_id),
        template_name = 'domains/record_list.html',
        extra_context = extra_context,
    )

@login_required
def soa_update(request, domain_id):
    user = request.user
    soa = get_object_or_404(SOA, user=request.user,pk=domain_id)
    if request.method == 'POST':
        form = SOAForm(request.POST, instance=soa)
        if form.is_valid():
            form.save()
    return HttpResponseRedirect(reverse(domain_detail, args=[domain_id]))


@login_required
def update_zone(request, domain_id, zone_id):
    user = request.user
    soa = get_object_or_404(SOA, user=request.user,pk=domain_id)
    zone = get_object_or_404(RR, pk=zone_id, zone=soa)
    if request.method == 'POST':
        form = RRForm(request.POST, instance=zone)
        if form.is_valid():
            update = request.POST.get('update')
            if update == 'Delete':
                zone.delete()
            else:
                form.save()
    return HttpResponseRedirect(reverse(domain_detail, args=[domain_id]))


@login_required
def add_zone(request, domain_id):
    user = request.user
    soa = get_object_or_404(SOA, user=request.user,pk=domain_id)
    if request.method == 'POST':
        if int(request.POST.get('zone')) == soa.id:
            form = RRForm(request.POST)
            if form.is_valid():
                form.save()
    return HttpResponseRedirect(reverse(domain_detail, args=[domain_id]))

